package com.spring.cloud.examples.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Iterator;
import java.util.List;
import java.util.Set;


/**
 * 签名过滤器
 */
@Component
public class GatewaySignFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("valid sign request  " + exchange.getRequest().getPath());
        ServerHttpRequest request =  exchange.getRequest() ;
        String method = exchange.getRequest().getMethodValue();
        if(method==null)
        {
            System.out.println(" method is null");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        HttpHeaders httpHeaders = request.getHeaders();
        List<String> signVlaues = httpHeaders.getValuesAsList("bbs-sign-header");
        if(CollectionUtils.isEmpty(signVlaues))
        {
            System.out.println(" bbs-sign-header is null ");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }

//        if(method.toUpperCase().equals("GET"))
//        {
//            Set<String> paramKeys = request.getQueryParams().keySet();
//            Iterator<String> paramKeyIt = paramKeys.iterator();
//            while(paramKeyIt.hasNext())
//            {
//                String paramKey = paramKeyIt.next();
//                request.getQueryParams().getFirst(paramKey);
//            }
//
//            MultiValueMap<String, String> queryParams =  request.getQueryParams();
//
//        }
//        if(method.toUpperCase().equals("POST"))
//        {
//            MediaType mediaType = httpHeaders.getContentType();
//            //JSON格式
//            if(mediaType.toString().toUpperCase().indexOf("APPLICATION/JSON")!=-1)
//            {
//
//            }
//            MultiValueMap<String, String> queryParams =  request.getQueryParams();
//
//        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -101;
    }
}
